# -*- coding: utf-8 -*-
from sqlalchemy.orm import Session
import app.models.articles as articles
import schemas

def get_article(db: Session, article_id: int):
    return db.query(articles.Article).filter(articles.Article.id == article_id).first()

def get_articles(db: Session, skip: int = 0, limit: int = 10):
    return db.query(articles.Article).offset(skip).limit(limit).all()

def create_article(db: Session, article:schemas.ArticleCreate):
    db_article = articles.Article(**article.model_dump())
    db.add(db_article)
    db.commit()
    db.refresh(db_article)
    return db_article

def update_article(db: Session, article_id: int, article:schemas.ArticleUpdate):
    db_article = get_article(db, article_id)
    if db_article:
        for var, value in vars(article).items():
            setattr(db_article, var, value) if value else None
        db.commit()
        db.refresh(db_article)
    return db_article

def delete_article(db: Session, article_id: int):
    db_article = get_article(db, article_id)
    if db_article:
        db.delete(db_article)
        db.commit()
    return db_article
